﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace JDKill.Utils
{
    class MusicPlayer
    {
        private IntPtr _handle = IntPtr.Zero;

        public MusicPlayer(IntPtr handle)
        {
            _handle = handle;
        }

        /// <summary>
        /// 声音和视频播放API函数
        /// </summary>
        /// <param name="lpstrCommand"></param>
        /// <param name="lpstrReturnString"></param>
        /// <param name="uReturnLength"></param>
        /// <param name="hwndCallback"></param>
        /// <returns></returns>
        [DllImport("winmm.dll", EntryPoint = "mciSendString", CharSet = CharSet.Auto)]
        public static extern int mciSendString(
            string lpstrCommand,
            string lpstrReturnString,
            int uReturnLength,
            int hwndCallback

            );

        /// <summary>
        /// 播放已经选择的声音文件
        /// </summary>
        public void Play(string filePath)
        {
            try
            {
                //System.Media.SoundPlayer player = new System.Media.SoundPlayer();
                //player.SoundLocation = filePath;
                //player.Load();
                //player.Play();

                //Audio audio = new Audio(fileName);
                //audio.Play();

                Stop();

                //打开  file 这个路径的歌曲 " ，type mpegvideo是文件类型  ，    alias 是将文件别名为media 
                mciSendString("open \"" + filePath + "\" type mpegvideo alias media", null, 0, 0);
                mciSendString("play media notify", null, 0, _handle.ToInt32());//播放
            }
            catch (Exception ex)
            {
            }
        }

        /// <summary>
        /// 关闭音乐
        /// </summary>
        public void Stop()
        {
            try
            {
                mciSendString("close media", null, 0, 0);
            }
            catch
            {
            }
        }
    }
}
